package com.zyx.xxl.executor.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.zyx.xxl.executor.domain.enums.ResultCodeEnum;
import com.zyx.xxl.executor.domain.enums.ResultMsgEnum;
import com.zyx.xxl.executor.domain.resp.FrontResult;
import com.zyx.xxl.executor.utils.TimeUtil;
import com.zyx.xxl.executor.utils.XxlJobUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * @author Yaxi.Zhang
 * @since 2022/6/13 18:33
 */
@RequestMapping(value = "/XxlJobController")
@RestController
public class XxlJobController {
    @Value("${xxl.job.admin.addresses}")
    private String adminAddresses;
    @Value("${xxl.job.executor.appname}")
    private String executorAppname;

    @GetMapping("/add")
    public FrontResult saveXxl() {
        //查询列表数据
        try {
            MultiValueMap requestInfo = new LinkedMultiValueMap();
            // ============================== 基础配置 ==============================
            // 执行器主键ID
            requestInfo.add("jobGroup", 1);
            // 执行器，任务Handler名称
            requestInfo.add("executorHandler", executorAppname);
            // 任务描述
            requestInfo.add("jobDesc", "xxl测试任务");
            // 负责人
            requestInfo.add("author", "admin");
            // 报警邮件
            // requestInfo.add("alarmEmail", "xxx@satcloud.com.cn");


            // ============================== 调度配置 ==============================
            // 调度类型
            requestInfo.add("scheduleType", "CRON");
            // 任务执行CRON表达式
            long etime1 = System.currentTimeMillis() + 60 * 1000; //延时函数，单位毫秒，这里是延时了1分钟
            String date = TimeUtil.formatDateByPattern(new Date(etime1));
            // requestInfo.put("jobCron","0 0/1 * * * ?");
            // requestInfo.add("jobCron", date);
            // CRON表达式
            // requestInfo.add("scheduleCOnf", date);
            requestInfo.add("scheduleConf", "0 0/1 * * * ?");



            // ============================== 任务配置 ==============================
            // GLUE类型    #com.xxl.job.core.glue.GlueTypeEnum
            requestInfo.add("glueType", "BEAN");
            // GLUE备注
            requestInfo.add("glueRemark", "GLUE代码初始化");
            // 执行器，任务参数
            // requestInfo.add("executorParam", "测试202006300943");

            // ============================== 高级配置 ==============================
            // 执行器路由策略
            requestInfo.add("executorRouteStrategy", "ROUND");
            // 调度过期策略
            requestInfo.add("misfireStrategy", "DO_NOTHING");
            // 阻塞处理策略
            requestInfo.add("executorBlockStrategy", "DISCARD_LATER");
            // 任务执行超时时间，单位秒
            requestInfo.add("executorTimeout", 0);
            // 失败重试次数
            requestInfo.add("executorFailRetryCount", 1);


            // 调度状态：0-停止，1-运行
            requestInfo.add("triggerStatus", 0);


            JSONObject frontResult = XxlJobUtil.addJob(requestInfo);
            System.out.println(frontResult);
            if (frontResult.containsKey("code") && 200 == (Integer) frontResult.get("code")) {
                //修改任务参数 把id放入
                // 执行器主键ID
                // requestInfo.put("executorParam", "JobId=" + FrontResultonse.get("content") + ";测试202006300943");
                requestInfo.put("id", Integer.valueOf(frontResult.get("content").toString()));
                JSONObject FrontResultonseUpdate = XxlJobUtil.updateJob(adminAddresses, requestInfo);
                if (FrontResultonseUpdate.containsKey("code") && 200 == (Integer) FrontResultonseUpdate.get("code")) {
                    //加入任务成功之后直接启动
                    JSONObject FrontResultonseStart = XxlJobUtil.startJob(Integer.parseInt(frontResult.get("content").toString()));
                    if (FrontResultonseStart.containsKey("code") && 200 == (Integer) FrontResultonseStart.get("code")) {
                        return FrontResult.getSuccessResult(ResultMsgEnum.FIND_SUCCESS.getMsg(), "创建成功");
                    } else {
                        throw new Exception("调用xxl-job-admin-start接口失败！");
                    }
                } else {
                    throw new Exception("调用xxl-job-admin-update接口失败！");
                }
            } else {
                throw new Exception("调用xxl-job-admin-add接口失败！");
            }
        } catch (Exception e) {
            //No HttpMessageConverter for com.alibaba.fastjson.JSONObject and content type "application/x-www-form-urlencoded"
            e.printStackTrace();
            return FrontResult.getExceptionResult(ResultCodeEnum.FAIL.getCode(), ResultMsgEnum.FIND_FAIL.getMsg());
        }
    }

    /**
     * 删除任务
     *
     * @param id 任务id
     */
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public FrontResult delete(int id) {
        try {
            JSONObject FrontResultonse = XxlJobUtil.deleteJob(id);
            if (FrontResultonse.containsKey("code") && 200 == (Integer) FrontResultonse.get("code")) {
                return FrontResult.getSuccessResult(ResultMsgEnum.FIND_SUCCESS.getMsg(), "删除成功");
            } else {
                throw new Exception("调用xxl-job-admin-delete接口失败！");
            }
        } catch (Exception e) {
            return FrontResult.getExceptionResult(ResultCodeEnum.FAIL.getCode(), ResultMsgEnum.FIND_FAIL.getMsg());
        }
    }

    /**
     * 开始任务
     *
     * @param id 任务id
     * @return
     * @throws
     */
    @RequestMapping(value = "/start", method = RequestMethod.GET)
    public FrontResult start(int id) {
        try {
            JSONObject result = XxlJobUtil.startJob(id);
            if (result.containsKey("code") && 200 == (Integer) result.get("code")) {
                return FrontResult.getSuccessResult(ResultMsgEnum.EXECUTE_SUCCESS.getMsg(), "开始Job任务成功,id" + id);
            } else {
                throw new Exception("调用xxl-job-admin-start接口失败！");
            }
        } catch (Exception e) {
            return FrontResult.getExceptionResult(ResultCodeEnum.FAIL.getCode(), ResultMsgEnum.EXECUTE_FAIL.getMsg());
        }
    }

    /**
     * 挂起任务
     *
     * @param id 任务id
     */
    @RequestMapping(value = "/stop", method = RequestMethod.GET)
    public FrontResult stop(int id) {
        try {
            JSONObject FrontResultonse = XxlJobUtil.stopJob(id);
            if (FrontResultonse.containsKey("code") && 200 == (Integer) FrontResultonse.get("code")) {
                return FrontResult.getSuccessResult(ResultMsgEnum.FIND_SUCCESS.getMsg(), "挂起job任务成功，id" + id);
            } else {
                throw new Exception("调用xxl-job-admin-stop接口失败！");
            }
        } catch (Exception e) {
            return FrontResult.getExceptionResult(ResultCodeEnum.FAIL.getCode(), ResultMsgEnum.FIND_FAIL.getMsg());
        }
    }

    /**
     * 登录xxl-job
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public FrontResult login() {
        System.out.println("开始登陆");
        try {
            String cookie = XxlJobUtil.login();
            System.out.println("=====>>>>> cookie" + cookie);
            if (StrUtil.isNotBlank(cookie)) {
                return FrontResult.getSuccessResult(ResultMsgEnum.FIND_SUCCESS.getMsg(), cookie);
            } else {
                throw new Exception("调用xxl-job-admin-login接口失败！");
            }
        } catch (Exception e) {
            return FrontResult.getExceptionResult(ResultCodeEnum.FAIL.getCode(), ResultMsgEnum.FIND_FAIL.getMsg());
        }
    }

    /**
     * 根据xxl-appname获取对应id
     */
    @RequestMapping(value = "/getAppNameIdByAppname", method = RequestMethod.GET)
    public FrontResult getAppNameIdByAppname() {
        try {
            JSONObject FrontResultonse = XxlJobUtil.getAppNameIdByAppname(adminAddresses, executorAppname);
            if (FrontResultonse.containsKey("code") && 200 == (Integer) FrontResultonse.get("code")) {
                return FrontResult.getSuccessResult(ResultMsgEnum.FIND_SUCCESS.getMsg(), "根据xxl-appname获取对应id");
            } else {
                throw new Exception("调用xxl-job-admin-getAppNameIdByAppname接口失败！");
            }
        } catch (Exception e) {
            return FrontResult.getExceptionResult(ResultCodeEnum.FAIL.getCode(), ResultMsgEnum.FIND_FAIL.getMsg());
        }
    }
}
